package org.example.curriculum_design_6_16.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.curriculum_design_6_16.entity.pojo.SocialService;
import org.example.curriculum_design_6_16.entity.pojo.SocialServiceRule;
import org.example.curriculum_design_6_16.entity.vo.Result;
import org.example.curriculum_design_6_16.entity.vo.SocialServiceVo;
import org.example.curriculum_design_6_16.mapper.SocialServiceMapper;
import org.example.curriculum_design_6_16.service.SocialServiceRuleService;
import org.example.curriculum_design_6_16.service.SocialServiceService;
import org.example.curriculum_design_6_16.service.StudentService;
import org.example.curriculum_design_6_16.service.impl.UserServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 社会服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/socialService")
public class SocialServiceController {
    @Autowired
    private SocialServiceRuleService socialServiceRuleService;

    @Autowired
    private SocialServiceService socialServiceService;

    @Autowired
    private SocialServiceMapper socialServiceMapper;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private StudentService studentService;

    /**
     * 计算学生社会服务总分
     */
    @GetMapping("/score/total")
    public Result<Double> getTotalScore(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            return Result.success(socialServiceService.calculateTotalSocialScore(studentId, academicYear));
        } catch (Exception e) {
            log.error("计算总分失败", e);
            return Result.error(500, "计算总分失败: " + e.getMessage());
        }
    }

    /**
     * 计算基础分
     */
    @GetMapping("/score/base")
    public Result<Double> getBaseScore(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            return Result.success(socialServiceService.calculateBaseScore(studentId, academicYear));
        } catch (Exception e) {
            log.error("计算基础分失败", e);
            return Result.error(500, "计算基础分失败: " + e.getMessage());
        }
    }

    /**
     * 计算附加分
     */
    @GetMapping("/score/additional")
    public Result<Double> getAdditionalScore(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            return Result.success(socialServiceService.calculateAdditionalScore(studentId, academicYear));
        } catch (Exception e) {
            log.error("计算附加分失败", e);
            return Result.error(500, "计算附加分失败: " + e.getMessage());
        }
    }

    /**
     * 获取学生社会服务等级
     */
    @GetMapping("/grade")
    public Result<String> getStudentGrade(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            return Result.success(socialServiceService.getStudentGrade(studentId, academicYear));
        } catch (Exception e) {
            log.error("获取等级失败", e);
            return Result.error(500, "获取等级失败: " + e.getMessage());
        }
    }

    /**
     * 获取学生社会服务统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStudentStatistics(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            return Result.success(socialServiceService.getStudentStatistics(studentId, academicYear));
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return Result.error(500, "获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 重新计算所有分数
     */
    @PostMapping("/recalculate")
    public Result<Boolean> recalculateScores(@RequestParam String studentId, @RequestParam String academicYear) {
        try {
            socialServiceService.calculateAndUpdateScores(studentId, academicYear);
            return Result.success(true);
        } catch (Exception e) {
            log.error("重新计算分数失败", e);
            return Result.error(500, "重新计算分数失败: " + e.getMessage());
        }
    }

    /**
     * 批量计算学生分数
     */
    @PostMapping("/batch-recalculate")
    public Result<Boolean> batchRecalculateScores(@RequestBody List<String> studentIds, @RequestParam String academicYear) {
        try {
            socialServiceService.batchCalculateScores(studentIds, academicYear);
            return Result.success(true);
        } catch (Exception e) {
            log.error("批量计算分数失败", e);
            return Result.error(500, "批量计算分数失败: " + e.getMessage());
        }
    }

    /**
     * 添加社会服务记录
     */
    @PostMapping("/add")
    public Result addRecord(@RequestBody SocialService record) {
        try {
            // 验证记录
            Map<String, Object> validation = socialServiceService.validateRecord(record);
            if (!(Boolean) validation.get("valid")) {
                return Result.error(400, "记录验证失败: " + validation.get("errors"));
            }

            // 设置默认状态为待审核
            record.setStatus(SocialService.STATUS_PENDING);
            int result = socialServiceService.insertSocialService(record);
            System.out.println();
            if (result > 0) {
                return Result.success(record.getId());
            }
            return Result.error(500, "添加记录失败");
        } catch (Exception e) {
            log.error("添加记录失败", e);
            return Result.error(500, "添加记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新社会服务记录
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateRecord(@PathVariable Integer id, @RequestBody SocialService record) {
        try {
            record.setId(id);
            
            // 验证记录
            Map<String, Object> validation = socialServiceService.validateRecord(record);
            if (!(Boolean) validation.get("valid")) {
                return Result.error(400, "记录验证失败: " + validation.get("errors"));
            }

            int result = socialServiceMapper.updateById(record);
            if (result > 0) {
                // 如果记录已通过审核，重新计算分数
                if (SocialService.STATUS_APPROVED.equals(record.getStatus())) {
                    socialServiceService.calculateAndUpdateScores(record.getStudentId(), record.getAcademicYear());
                }
                return Result.success(true);
            }
            return Result.error(500, "更新记录失败");
        } catch (Exception e) {
            log.error("更新记录失败", e);
            return Result.error(500, "更新记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除社会服务记录
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteRecord(@PathVariable Integer id) {
        try {
            SocialService record = socialServiceMapper.selectById(id);
            if (record == null) {
                return Result.error(404, "记录不存在");
            }

            int result = socialServiceMapper.deleteById(id);
            if (result > 0) {
                // 如果记录已通过审核，重新计算分数
                if (SocialService.STATUS_APPROVED.equals(record.getStatus())) {
                    socialServiceService.calculateAndUpdateScores(record.getStudentId(), record.getAcademicYear());
                }
                return Result.success(true);
            }
            return Result.error(500, "删除记录失败");
        } catch (Exception e) {
            log.error("删除记录失败", e);
            return Result.error(500, "删除记录失败: " + e.getMessage());
        }
    }

//    /**
//     * 获取学生的年度社会服务记录
//     */
//    @GetMapping("/academicYear")
//    public Result<List<SocialService>> getAcademicYearRecords(
//            @RequestParam String studentId,
//            @RequestParam String academicYear) {
//        try {
//            List<SocialService> records = socialServiceMapper.findByStudentIdAndYear(studentId, academicYear);
//            return Result.success(records);
//        } catch (Exception e) {
//            log.error("获取记录失败", e);
//            return Result.error(500, "获取记录失败: " + e.getMessage());
//        }
//    }

    /**
     * 获取学生的所有社会服务记录
     */
    @GetMapping("/student/{studentId}")
    public Result getRecords(@PathVariable String studentId) {
        try {
            String studentName = studentService.getStudentById(studentId).getName();
            List<SocialService> records = socialServiceMapper.findByStudentId(studentId);

            List<SocialServiceVo> voList = records.stream()
                    .map(record -> {
                        SocialServiceVo vo = new SocialServiceVo();
                        // 使用 BeanUtils 复制属性（需要引入 spring-beans）
                        BeanUtils.copyProperties(record, vo);
                        vo.setStudentName(studentName);
                        return vo;
                    })
                    .collect(Collectors.toList());
            return Result.success(voList);
        } catch (Exception e) {
            log.error("获取记录失败", e);
            return Result.error(500, "获取记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取待审核的记录
     */
    @GetMapping("/pending")
    public Result<List<SocialService>> getPendingRecords() {
        try {
            List<SocialService> records = socialServiceService.getPendingRecords();
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取待审核记录失败", e);
            return Result.error(500, "获取待审核记录失败: " + e.getMessage());
        }
    }

    /**
     * 审核社会服务记录
     */
    @PostMapping("/{id}/review")
    public Result<Boolean> reviewRecord(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> request) {
        try {
            Integer status = (Integer) request.get("status");
            String comment = (String) request.get("comment");
            
            if (status == null) {
                return Result.error(400, "审核状态不能为空");
            }

            socialServiceService.reviewRecord(id, status, comment);
            return Result.success(true);
        } catch (Exception e) {
            log.error("审核记录失败", e);
            return Result.error(500, "审核记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取社会服务规则映射
     */
    @GetMapping("/rules")
    public Result<Map<String, SocialServiceRule>> getRules() {
        try {
            Map<String, SocialServiceRule> rules = socialServiceService.getRuleMap();
            return Result.success(rules);
        } catch (Exception e) {
            log.error("获取规则失败", e);
            return Result.error(500, "获取规则失败: " + e.getMessage());
        }
    }

    /**
     * 验证社会服务记录
     */
    @PostMapping("/validate")
    public Result<Map<String, Object>> validateRecord(@RequestBody SocialService record) {
        try {
            Map<String, Object> validation = socialServiceService.validateRecord(record);
            return Result.success(validation);
        } catch (Exception e) {
            log.error("验证记录失败", e);
            return Result.error(500, "验证记录失败: " + e.getMessage());
        }
    }
}
